


<!DOCTYPE html>
<!--[if IE 8]><html class="no-js lt-ie9" lang="en" > <![endif]-->
<!--[if gt IE 8]><!--> <html class="no-js" lang="en" > <!--<![endif]-->
<head>
  <meta charset="utf-8">
  
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  
  <title>torch.utils.data &mdash; PyTorch master documentation</title>
  

  
  
  
  
    <link rel="canonical" href="https://pytorch.org/docs/stable/data.html"/>
  

  

  
  
    

  

  <link rel="stylesheet" href="_static/css/theme.css" type="text/css" />
  <!-- <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.10.0-beta/dist/katex.min.css" type="text/css" />
  <link rel="stylesheet" href="_static/css/jit.css" type="text/css" />
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.11.1/dist/katex.min.css" type="text/css" />
  <link rel="stylesheet" href="_static/katex-math.css" type="text/css" />
    <link rel="index" title="Index" href="genindex.html" />
    <link rel="search" title="Search" href="search.html" />
    <link rel="next" title="torch.utils.dlpack" href="dlpack.html" />
    <link rel="prev" title="torch.utils.cpp_extension" href="cpp_extension.html" /> 

  
  <script src="_static/js/modernizr.min.js"></script>

  <!-- Preload the theme fonts -->

<link rel="preload" href="_static/fonts/FreightSans/freight-sans-book.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="_static/fonts/FreightSans/freight-sans-medium.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="_static/fonts/IBMPlexMono/IBMPlexMono-Medium.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="_static/fonts/FreightSans/freight-sans-bold.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="_static/fonts/FreightSans/freight-sans-medium-italic.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="_static/fonts/IBMPlexMono/IBMPlexMono-SemiBold.woff2" as="font" type="font/woff2" crossorigin="anonymous">

<!-- Preload the katex fonts -->

<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Math-Italic.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Main-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Main-Bold.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Size1-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Size4-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Size2-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Size3-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
<link rel="preload" href="https://cdn.jsdelivr.net/npm/katex@0.10.0/dist/fonts/KaTeX_Caligraphic-Regular.woff2" as="font" type="font/woff2" crossorigin="anonymous">
</head>

<div class="container-fluid header-holder tutorials-header" id="header-holder">
  <div class="container">
    <div class="header-container">
      <a class="header-logo" href="https://pytorch.org/" aria-label="PyTorch"></a>

      <div class="main-menu">
        <ul>
          <li>
            <a href="https://pytorch.org/get-started">Get Started</a>
          </li>

          <li>
            <div class="ecosystem-dropdown">
              <a id="dropdownMenuButton" data-toggle="ecosystem-dropdown">
                Ecosystem
              </a>
              <div class="ecosystem-dropdown-menu">
                <a class="nav-dropdown-item" href="https://pytorch.org/hub"">
                  <span class=dropdown-title>Models (Beta)</span>
                  <p>Discover, publish, and reuse pre-trained models</p>
                </a>
                <a class="nav-dropdown-item" href="https://pytorch.org/ecosystem">
                  <span class=dropdown-title>Tools & Libraries</span>
                  <p>Explore the ecosystem of tools and libraries</p>
                </a>
              </div>
            </div>
          </li>

          <li>
            <a href="https://pytorch.org/mobile">Mobile</a>
          </li>

          <li>
            <a href="https://pytorch.org/blog/">Blog</a>
          </li>

          <li>
            <a href="https://pytorch.org/tutorials">Tutorials</a>
          </li>

          <li class="active">
            <a href="https://pytorch.org/docs/stable/index.html">Docs</a>
          </li>

          <li>
            <div class="resources-dropdown">
              <a id="resourcesDropdownButton" data-toggle="resources-dropdown">
                Resources
              </a>
              <div class="resources-dropdown-menu">
                <a class="nav-dropdown-item" href="https://pytorch.org/resources"">
                  <span class=dropdown-title>Developer Resources</span>
                  <p>Find resources and get questions answered</p>
                </a>
                <a class="nav-dropdown-item" href="https://pytorch.org/features">
                  <span class=dropdown-title>About</span>
                  <p>Learn about PyTorch’s features and capabilities</p>
                </a>
              </div>
            </div>
          </li>

          <li>
            <a href="https://github.com/pytorch/pytorch">Github</a>
          </li>
        </ul>
      </div>

      <a class="main-menu-open-button" href="#" data-behavior="open-mobile-menu"></a>
    </div>

  </div>
</div>


<body class="pytorch-body">

   

    

    <div class="table-of-contents-link-wrapper">
      <span>Table of Contents</span>
      <a href="#" class="toggle-table-of-contents" data-behavior="toggle-table-of-contents"></a>
    </div>

    <nav data-toggle="wy-nav-shift" class="pytorch-left-menu" id="pytorch-left-menu">
      <div class="pytorch-side-scroll">
        <div class="pytorch-menu pytorch-menu-vertical" data-spy="affix" role="navigation" aria-label="main navigation">
          <div class="pytorch-left-menu-search">
            

            
              
              
                <div class="version">
                  master (1.5.0 )
                </div>
              
            

            


  


<div role="search">
  <form id="rtd-search-form" class="wy-form" action="search.html" method="get">
    <input type="text" name="q" placeholder="Search Docs" />
    <input type="hidden" name="check_keywords" value="yes" />
    <input type="hidden" name="area" value="default" />
  </form>
</div>

            
          </div>

          
<div>
  <a style="color:#F05732" href="https://pytorch.org/docs/stable/data.html">
    You are viewing unstable developer preview docs.
    Click here to view docs for latest stable release.
  </a>
</div>

            
            
              
            
            
              <p class="caption"><span class="caption-text">Notes</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="notes/amp_examples.html">Automatic Mixed Precision examples</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/autograd.html">Autograd mechanics</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/broadcasting.html">Broadcasting semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/cpu_threading_torchscript_inference.html">CPU threading and TorchScript inference</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/cuda.html">CUDA semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/ddp.html">Distributed Data Parallel</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/extending.html">Extending PyTorch</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/faq.html">Frequently Asked Questions</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/large_scale_deployments.html">Features for large-scale deployments</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/multiprocessing.html">Multiprocessing best practices</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/randomness.html">Reproducibility</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/serialization.html">Serialization semantics</a></li>
<li class="toctree-l1"><a class="reference internal" href="notes/windows.html">Windows FAQ</a></li>
</ul>
<p class="caption"><span class="caption-text">Language Bindings</span></p>
<ul>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/cppdocs/">C++ API</a></li>
<li class="toctree-l1"><a class="reference internal" href="packages.html">Javadoc</a></li>
</ul>
<p class="caption"><span class="caption-text">Python API</span></p>
<ul class="current">
<li class="toctree-l1"><a class="reference internal" href="torch.html">torch</a></li>
<li class="toctree-l1"><a class="reference internal" href="nn.html">torch.nn</a></li>
<li class="toctree-l1"><a class="reference internal" href="nn.functional.html">torch.nn.functional</a></li>
<li class="toctree-l1"><a class="reference internal" href="tensors.html">torch.Tensor</a></li>
<li class="toctree-l1"><a class="reference internal" href="tensor_attributes.html">Tensor Attributes</a></li>
<li class="toctree-l1"><a class="reference internal" href="tensor_view.html">Tensor Views</a></li>
<li class="toctree-l1"><a class="reference internal" href="autograd.html">torch.autograd</a></li>
<li class="toctree-l1"><a class="reference internal" href="cuda.html">torch.cuda</a></li>
<li class="toctree-l1"><a class="reference internal" href="amp.html">torch.cuda.amp</a></li>
<li class="toctree-l1"><a class="reference internal" href="distributed.html">torch.distributed</a></li>
<li class="toctree-l1"><a class="reference internal" href="distributions.html">torch.distributions</a></li>
<li class="toctree-l1"><a class="reference internal" href="hub.html">torch.hub</a></li>
<li class="toctree-l1"><a class="reference internal" href="jit.html">torch.jit</a></li>
<li class="toctree-l1"><a class="reference internal" href="nn.init.html">torch.nn.init</a></li>
<li class="toctree-l1"><a class="reference internal" href="onnx.html">torch.onnx</a></li>
<li class="toctree-l1"><a class="reference internal" href="optim.html">torch.optim</a></li>
<li class="toctree-l1"><a class="reference internal" href="quantization.html">Quantization</a></li>
<li class="toctree-l1"><a class="reference internal" href="rpc/index.html">Distributed RPC Framework</a></li>
<li class="toctree-l1"><a class="reference internal" href="random.html">torch.random</a></li>
<li class="toctree-l1"><a class="reference internal" href="sparse.html">torch.sparse</a></li>
<li class="toctree-l1"><a class="reference internal" href="storage.html">torch.Storage</a></li>
<li class="toctree-l1"><a class="reference internal" href="bottleneck.html">torch.utils.bottleneck</a></li>
<li class="toctree-l1"><a class="reference internal" href="checkpoint.html">torch.utils.checkpoint</a></li>
<li class="toctree-l1"><a class="reference internal" href="cpp_extension.html">torch.utils.cpp_extension</a></li>
<li class="toctree-l1 current"><a class="current reference internal" href="#">torch.utils.data</a></li>
<li class="toctree-l1"><a class="reference internal" href="dlpack.html">torch.utils.dlpack</a></li>
<li class="toctree-l1"><a class="reference internal" href="model_zoo.html">torch.utils.model_zoo</a></li>
<li class="toctree-l1"><a class="reference internal" href="tensorboard.html">torch.utils.tensorboard</a></li>
<li class="toctree-l1"><a class="reference internal" href="type_info.html">Type Info</a></li>
<li class="toctree-l1"><a class="reference internal" href="named_tensor.html">Named Tensors</a></li>
<li class="toctree-l1"><a class="reference internal" href="name_inference.html">Named Tensors operator coverage</a></li>
<li class="toctree-l1"><a class="reference internal" href="__config__.html">torch.__config__</a></li>
</ul>
<p class="caption"><span class="caption-text">Libraries</span></p>
<ul>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/audio">torchaudio</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/text">torchtext</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/elastic/">TorchElastic</a></li>
<li class="toctree-l1"><a class="reference external" href="https://pytorch.org/serve">TorchServe</a></li>
<li class="toctree-l1"><a class="reference external" href="http://pytorch.org/xla/">PyTorch on XLA Devices</a></li>
</ul>
<p class="caption"><span class="caption-text">Community</span></p>
<ul>
<li class="toctree-l1"><a class="reference internal" href="community/contribution_guide.html">PyTorch Contribution Guide</a></li>
<li class="toctree-l1"><a class="reference internal" href="community/governance.html">PyTorch Governance</a></li>
<li class="toctree-l1"><a class="reference internal" href="community/persons_of_interest.html">PyTorch Governance | Persons of Interest</a></li>
</ul>

            
          

        </div>
      </div>
    </nav>

    <div class="pytorch-container">
      <div class="pytorch-page-level-bar" id="pytorch-page-level-bar">
        <div class="pytorch-breadcrumbs-wrapper">
          















<div role="navigation" aria-label="breadcrumbs navigation">

  <ul class="pytorch-breadcrumbs">
    
      <li>
        <a href="index.html">
          
            Docs
          
        </a> &gt;
      </li>

        
      <li>torch.utils.data</li>
    
    
      <li class="pytorch-breadcrumbs-aside">
        
            
            <a href="_sources/data.rst.txt" rel="nofollow"><img src="_static/images/view-page-source-icon.svg"></a>
          
        
      </li>
    
  </ul>

  
</div>
        </div>

        <div class="pytorch-shortcuts-wrapper" id="pytorch-shortcuts-wrapper">
          Shortcuts
        </div>
      </div>

      <section data-toggle="wy-nav-shift" id="pytorch-content-wrap" class="pytorch-content-wrap">
        <div class="pytorch-content-left">

        
          
          <div class="rst-content">
          
            <div role="main" class="main-content" itemscope="itemscope" itemtype="http://schema.org/Article">
             <article itemprop="articleBody" id="pytorch-article" class="pytorch-article">
              
  <div class="section" id="module-torch.utils.data">
<span id="torch-utils-data"></span><h1>torch.utils.data<a class="headerlink" href="#module-torch.utils.data" title="Permalink to this headline">¶</a></h1>
<p>At the heart of PyTorch data loading utility is the <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">torch.utils.data.DataLoader</span></code></a>
class.  It represents a Python iterable over a dataset, with support for</p>
<ul class="simple">
<li><p><a class="reference internal" href="#dataset-types">map-style and iterable-style datasets</a>,</p></li>
<li><p><a class="reference internal" href="#data-loading-order-and-sampler">customizing data loading order</a>,</p></li>
<li><p><a class="reference internal" href="#loading-batched-and-non-batched-data">automatic batching</a>,</p></li>
<li><p><a class="reference internal" href="#single-and-multi-process-data-loading">single- and multi-process data loading</a>,</p></li>
<li><p><a class="reference internal" href="#memory-pinning">automatic memory pinning</a>.</p></li>
</ul>
<p>These options are configured by the constructor arguments of a
<a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>, which has signature:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">DataLoader</span><span class="p">(</span><span class="n">dataset</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="mi">1</span><span class="p">,</span> <span class="n">shuffle</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">sampler</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
           <span class="n">batch_sampler</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span> <span class="n">collate_fn</span><span class="o">=</span><span class="kc">None</span><span class="p">,</span>
           <span class="n">pin_memory</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">drop_last</span><span class="o">=</span><span class="kc">False</span><span class="p">,</span> <span class="n">timeout</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
           <span class="n">worker_init_fn</span><span class="o">=</span><span class="kc">None</span><span class="p">)</span>
</pre></div>
</div>
<p>The sections below describe in details the effects and usages of these options.</p>
<div class="section" id="dataset-types">
<h2>Dataset Types<a class="headerlink" href="#dataset-types" title="Permalink to this headline">¶</a></h2>
<p>The most important argument of <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>
constructor is <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code>, which indicates a dataset object to load data
from. PyTorch supports two different types of datasets:</p>
<ul class="simple">
<li><p><a class="reference internal" href="#map-style-datasets">map-style datasets</a>,</p></li>
<li><p><a class="reference internal" href="#iterable-style-datasets">iterable-style datasets</a>.</p></li>
</ul>
<div class="section" id="map-style-datasets">
<h3>Map-style datasets<a class="headerlink" href="#map-style-datasets" title="Permalink to this headline">¶</a></h3>
<p>A map-style dataset is one that implements the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code> and
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code> protocols, and represents a map from (possibly non-integral)
indices/keys to data samples.</p>
<p>For example, such a dataset, when accessed with <code class="docutils literal notranslate"><span class="pre">dataset[idx]</span></code>, could read
the <code class="docutils literal notranslate"><span class="pre">idx</span></code>-th image and its corresponding label from a folder on the disk.</p>
<p>See <a class="reference internal" href="#torch.utils.data.Dataset" title="torch.utils.data.Dataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dataset</span></code></a> for more details.</p>
</div>
<div class="section" id="iterable-style-datasets">
<h3>Iterable-style datasets<a class="headerlink" href="#iterable-style-datasets" title="Permalink to this headline">¶</a></h3>
<p>An iterable-style dataset is an instance of a subclass of <a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a>
that implements the <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code> protocol, and represents an iterable over
data samples. This type of datasets is particularly suitable for cases where
random reads are expensive or even improbable, and where the batch size depends
on the fetched data.</p>
<p>For example, such a dataset, when called <code class="docutils literal notranslate"><span class="pre">iter(dataset)</span></code>, could return a
stream of data reading from a database, a remote server, or even logs generated
in real time.</p>
<p>See <a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a> for more details.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>When using an <a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a> with
<a class="reference internal" href="#multi-process-data-loading">multi-process data loading</a>. The same
dataset object is replicated on each worker process, and thus the
replicas must be configured differently to avoid duplicated data. See
<a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a> documentations for how to
achieve this.</p>
</div>
</div>
</div>
<div class="section" id="data-loading-order-and-sampler">
<h2>Data Loading Order and <a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sampler</span></code></a><a class="headerlink" href="#data-loading-order-and-sampler" title="Permalink to this headline">¶</a></h2>
<p>For <a class="reference internal" href="#iterable-style-datasets">iterable-style datasets</a>, data loading order
is entirely controlled by the user-defined iterable. This allows easier
implementations of chunk-reading and dynamic batch size (e.g., by yielding a
batched sample at each time).</p>
<p>The rest of this section concerns the case with
<a class="reference internal" href="#map-style-datasets">map-style datasets</a>. <a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><code class="xref py py-class docutils literal notranslate"><span class="pre">torch.utils.data.Sampler</span></code></a>
classes are used to specify the sequence of indices/keys used in data loading.
They represent iterable objects over the indices to datasets.  E.g., in the
common case with stochastic gradient decent (SGD), a
<a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sampler</span></code></a> could randomly permute a list of indices
and yield each one at a time, or yield a small number of them for mini-batch
SGD.</p>
<p>A sequential or shuffled sampler will be automatically constructed based on the <code class="xref py py-attr docutils literal notranslate"><span class="pre">shuffle</span></code> argument to a <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>.
Alternatively, users may use the <code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code> argument to specify a
custom <a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sampler</span></code></a> object that at each time yields
the next index/key to fetch.</p>
<p>A custom <a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sampler</span></code></a> that yields a list of batch
indices at a time can be passed as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_sampler</span></code> argument.
Automatic batching can also be enabled via <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_size</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">drop_last</span></code> arguments. See
<a class="reference internal" href="#loading-batched-and-non-batched-data">the next section</a> for more details
on this.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Neither <code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code> nor <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_sampler</span></code> is compatible with
iterable-style datasets, since such datasets have no notion of a key or an
index.</p>
</div>
</div>
<div class="section" id="loading-batched-and-non-batched-data">
<h2>Loading Batched and Non-Batched Data<a class="headerlink" href="#loading-batched-and-non-batched-data" title="Permalink to this headline">¶</a></h2>
<p><a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> supports automatically collating
individual fetched data samples into batches via arguments
<code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_size</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">drop_last</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_sampler</span></code>.</p>
<div class="section" id="automatic-batching-default">
<h3>Automatic batching (default)<a class="headerlink" href="#automatic-batching-default" title="Permalink to this headline">¶</a></h3>
<p>This is the most common case, and corresponds to fetching a minibatch of
data and collating them into batched samples, i.e., containing Tensors with
one dimension being the batch dimension (usually the first).</p>
<p>When <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_size</span></code> (default <code class="docutils literal notranslate"><span class="pre">1</span></code>) is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the data loader yields
batched samples instead of individual samples. <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_size</span></code> and
<code class="xref py py-attr docutils literal notranslate"><span class="pre">drop_last</span></code> arguments are used to specify how the data loader obtains
batches of dataset keys. For map-style datasets, users can alternatively
specify <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_sampler</span></code>, which yields a list of keys at a time.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_size</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">drop_last</span></code> arguments essentially are used
to construct a <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_sampler</span></code> from <code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code>. For map-style
datasets, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code> is either provided by user or constructed
based on the <code class="xref py py-attr docutils literal notranslate"><span class="pre">shuffle</span></code> argument. For iterable-style datasets, the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code> is a dummy infinite one. See
<a class="reference internal" href="#data-loading-order-and-sampler">this section</a> on more details on
samplers.</p>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>When fetching from
<a class="reference internal" href="#iterable-style-datasets">iterable-style datasets</a> with
<a class="reference internal" href="#multi-process-data-loading">multi-processing</a>, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">drop_last</span></code>
argument drops the last non-full batch of each worker’s dataset replica.</p>
</div>
<p>After fetching a list of samples using the indices from sampler, the function
passed as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> argument is used to collate lists of samples
into batches.</p>
<p>In this case, loading from a map-style dataset is roughly equivalent with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">indices</span> <span class="ow">in</span> <span class="n">batch_sampler</span><span class="p">:</span>
    <span class="k">yield</span> <span class="n">collate_fn</span><span class="p">([</span><span class="n">dataset</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">])</span>
</pre></div>
</div>
<p>and loading from an iterable-style dataset is roughly equivalent with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="n">dataset_iter</span> <span class="o">=</span> <span class="nb">iter</span><span class="p">(</span><span class="n">dataset</span><span class="p">)</span>
<span class="k">for</span> <span class="n">indices</span> <span class="ow">in</span> <span class="n">batch_sampler</span><span class="p">:</span>
    <span class="k">yield</span> <span class="n">collate_fn</span><span class="p">([</span><span class="nb">next</span><span class="p">(</span><span class="n">dataset_iter</span><span class="p">)</span> <span class="k">for</span> <span class="n">_</span> <span class="ow">in</span> <span class="n">indices</span><span class="p">])</span>
</pre></div>
</div>
<p>A custom <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> can be used to customize collation, e.g., padding
sequential data to max length of a batch. See
<a class="reference internal" href="#dataloader-collate-fn">this section</a> on more about <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code>.</p>
</div>
<div class="section" id="disable-automatic-batching">
<h3>Disable automatic batching<a class="headerlink" href="#disable-automatic-batching" title="Permalink to this headline">¶</a></h3>
<p>In certain cases, users may want to handle batching manually in dataset code,
or simply load individual samples. For example, it could be cheaper to directly
load batched data (e.g., bulk reads from a database or reading continuous
chunks of memory), or the batch size is data dependent, or the program is
designed to work on individual samples.  Under these scenarios, it’s likely
better to not use automatic batching (where <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> is used to
collate the samples), but let the data loader directly return each member of
the <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code> object.</p>
<p>When both <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_size</span></code> and <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_sampler</span></code> are <code class="docutils literal notranslate"><span class="pre">None</span></code> (default
value for <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_sampler</span></code> is already <code class="docutils literal notranslate"><span class="pre">None</span></code>), automatic batching is
disabled. Each sample obtained from the <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code> is processed with the
function passed as the <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> argument.</p>
<p><strong>When automatic batching is disabled</strong>, the default <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> simply
converts NumPy arrays into PyTorch Tensors, and keeps everything else untouched.</p>
<p>In this case, loading from a map-style dataset is roughly equivalent with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">index</span> <span class="ow">in</span> <span class="n">sampler</span><span class="p">:</span>
    <span class="k">yield</span> <span class="n">collate_fn</span><span class="p">(</span><span class="n">dataset</span><span class="p">[</span><span class="n">index</span><span class="p">])</span>
</pre></div>
</div>
<p>and loading from an iterable-style dataset is roughly equivalent with:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">for</span> <span class="n">data</span> <span class="ow">in</span> <span class="nb">iter</span><span class="p">(</span><span class="n">dataset</span><span class="p">):</span>
    <span class="k">yield</span> <span class="n">collate_fn</span><span class="p">(</span><span class="n">data</span><span class="p">)</span>
</pre></div>
</div>
<p>See <a class="reference internal" href="#dataloader-collate-fn">this section</a> on more about <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code>.</p>
</div>
<div class="section" id="working-with-collate-fn">
<span id="dataloader-collate-fn"></span><h3>Working with <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code><a class="headerlink" href="#working-with-collate-fn" title="Permalink to this headline">¶</a></h3>
<p>The use of <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> is slightly different when automatic batching is
enabled or disabled.</p>
<p><strong>When automatic batching is disabled</strong>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> is called with
each individual data sample, and the output is yielded from the data loader
iterator. In this case, the default <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> simply converts NumPy
arrays in PyTorch tensors.</p>
<p><strong>When automatic batching is enabled</strong>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> is called with a list
of data samples at each time. It is expected to collate the input samples into
a batch for yielding from the data loader iterator. The rest of this section
describes behavior of the default <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> in this case.</p>
<p>For instance, if each data sample consists of a 3-channel image and an integral
class label, i.e., each element of the dataset returns a tuple
<code class="docutils literal notranslate"><span class="pre">(image,</span> <span class="pre">class_index)</span></code>, the default <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> collates a list of
such tuples into a single tuple of a batched image tensor and a batched class
label Tensor. In particular, the default <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> has the following
properties:</p>
<ul class="simple">
<li><p>It always prepends a new dimension as the batch dimension.</p></li>
<li><p>It automatically converts NumPy arrays and Python numerical values into
PyTorch Tensors.</p></li>
<li><p>It preserves the data structure, e.g., if each sample is a dictionary, it
outputs a dictionary with the same set of keys but batched Tensors as values
(or lists if the values can not be converted into Tensors). Same
for <code class="docutils literal notranslate"><span class="pre">list</span></code> s, <code class="docutils literal notranslate"><span class="pre">tuple</span></code> s, <code class="docutils literal notranslate"><span class="pre">namedtuple</span></code> s, etc.</p></li>
</ul>
<p>Users may use customized <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> to achieve custom batching, e.g.,
collating along a dimension other than the first, padding sequences of
various lengths, or adding support for custom data types.</p>
</div>
</div>
<div class="section" id="single-and-multi-process-data-loading">
<h2>Single- and Multi-process Data Loading<a class="headerlink" href="#single-and-multi-process-data-loading" title="Permalink to this headline">¶</a></h2>
<p>A <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> uses single-process data loading by
default.</p>
<p>Within a Python process, the
<a class="reference external" href="https://wiki.python.org/moin/GlobalInterpreterLock">Global Interpreter Lock (GIL)</a>
prevents true fully parallelizing Python code across threads. To avoid blocking
computation code with data loading, PyTorch provides an easy switch to perform
multi-process data loading by simply setting the argument <code class="xref py py-attr docutils literal notranslate"><span class="pre">num_workers</span></code>
to a positive integer.</p>
<div class="section" id="single-process-data-loading-default">
<h3>Single-process data loading (default)<a class="headerlink" href="#single-process-data-loading-default" title="Permalink to this headline">¶</a></h3>
<p>In this mode, data fetching is done in the same process a
<a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> is initialized.  Therefore, data loading
may block computing.  However, this mode may be preferred when resource(s) used
for sharing data among processes (e.g., shared memory, file descriptors) is
limited, or when the entire dataset is small and can be loaded entirely in
memory.  Additionally, single-process loading often shows more readable error
traces and thus is useful for debugging.</p>
</div>
<div class="section" id="multi-process-data-loading">
<h3>Multi-process data loading<a class="headerlink" href="#multi-process-data-loading" title="Permalink to this headline">¶</a></h3>
<p>Setting the argument <code class="xref py py-attr docutils literal notranslate"><span class="pre">num_workers</span></code> as a positive integer will
turn on multi-process data loading with the specified number of loader worker
processes.</p>
<p>In this mode, each time an iterator of a <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>
is created (e.g., when you call <code class="docutils literal notranslate"><span class="pre">enumerate(dataloader)</span></code>), <code class="xref py py-attr docutils literal notranslate"><span class="pre">num_workers</span></code>
worker processes are created. At this point, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code> are passed to each
worker, where they are used to initialize, and fetch data. This means that
dataset access together with its  internal IO, transforms
(including <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code>) runs in the worker process.</p>
<p><a class="reference internal" href="#torch.utils.data.get_worker_info" title="torch.utils.data.get_worker_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.utils.data.get_worker_info()</span></code></a> returns various useful information
in a worker process (including the worker id, dataset replica, initial seed,
etc.), and returns <code class="docutils literal notranslate"><span class="pre">None</span></code> in main process. Users may use this function in
dataset code and/or <code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code> to individually configure each
dataset replica, and to determine whether the code is running in a worker
process. For example, this can be particularly helpful in sharding the dataset.</p>
<p>For map-style datasets, the main process generates the indices using
<code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code> and sends them to the workers. So any shuffle randomization is
done in the main process which guides loading by assigning indices to load.</p>
<p>For iterable-style datasets, since each worker process gets a replica of the
<code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code> object, naive multi-process loading will often result in
duplicated data. Using <a class="reference internal" href="#torch.utils.data.get_worker_info" title="torch.utils.data.get_worker_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.utils.data.get_worker_info()</span></code></a> and/or
<code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code>, users may configure each replica independently. (See
<a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a> documentations for how to achieve
this. ) For similar reasons, in multi-process loading, the <code class="xref py py-attr docutils literal notranslate"><span class="pre">drop_last</span></code>
argument drops the last non-full batch of each worker’s iterable-style dataset
replica.</p>
<p>Workers are shut down once the end of the iteration is reached, or when the
iterator becomes garbage collected.</p>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>It is generally not recommended to return CUDA tensors in multi-process
loading because of many subtleties in using CUDA and sharing CUDA tensors in
multiprocessing (see <a class="reference internal" href="notes/multiprocessing.html#multiprocessing-cuda-note"><span class="std std-ref">CUDA in multiprocessing</span></a>). Instead, we recommend
using <a class="reference internal" href="#memory-pinning">automatic memory pinning</a> (i.e., setting
<code class="xref py py-attr docutils literal notranslate"><span class="pre">pin_memory=True</span></code>), which enables fast data transfer to CUDA-enabled
GPUs.</p>
</div>
<div class="section" id="platform-specific-behaviors">
<h4>Platform-specific behaviors<a class="headerlink" href="#platform-specific-behaviors" title="Permalink to this headline">¶</a></h4>
<p>Since workers rely on Python <a class="reference external" href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing" title="(in Python v3.8)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a>, worker launch behavior is
different on Windows compared to Unix.</p>
<ul class="simple">
<li><p>On Unix, <code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code> is the default <a class="reference external" href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing" title="(in Python v3.8)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> start method.
Using <code class="xref py py-func docutils literal notranslate"><span class="pre">fork()</span></code>, child workers typically can access the <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code> and
Python argument functions directly through the cloned address space.</p></li>
<li><p>On Windows, <code class="xref py py-func docutils literal notranslate"><span class="pre">spawn()</span></code> is the default <a class="reference external" href="https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing" title="(in Python v3.8)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">multiprocessing</span></code></a> start method.
Using <code class="xref py py-func docutils literal notranslate"><span class="pre">spawn()</span></code>, another interpreter is launched which runs your main script,
followed by the internal worker function that receives the <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> and other arguments through <a class="reference external" href="https://docs.python.org/3/library/pickle.html#module-pickle" title="(in Python v3.8)"><code class="xref py py-mod docutils literal notranslate"><span class="pre">pickle</span></code></a> serialization.</p></li>
</ul>
<p>This separate serialization means that you should take two steps to ensure you
are compatible with Windows while using multi-process data loading:</p>
<ul class="simple">
<li><p>Wrap most of you main script’s code within <code class="docutils literal notranslate"><span class="pre">if</span> <span class="pre">__name__</span> <span class="pre">==</span> <span class="pre">'__main__':</span></code> block,
to make sure it doesn’t run again (most likely generating error) when each worker
process is launched. You can place your dataset and <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>
instance creation logic here, as it doesn’t need to be re-executed in workers.</p></li>
<li><p>Make sure that any custom <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code>
or <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code> code is declared as top level definitions, outside of the
<code class="docutils literal notranslate"><span class="pre">__main__</span></code> check. This ensures that they are available in worker processes.
(this is needed since functions are pickled as references only, not <code class="docutils literal notranslate"><span class="pre">bytecode</span></code>.)</p></li>
</ul>
</div>
<div class="section" id="randomness-in-multi-process-data-loading">
<h4>Randomness in multi-process data loading<a class="headerlink" href="#randomness-in-multi-process-data-loading" title="Permalink to this headline">¶</a></h4>
<p>By default, each worker will have its PyTorch seed set to <code class="docutils literal notranslate"><span class="pre">base_seed</span> <span class="pre">+</span> <span class="pre">worker_id</span></code>,
where <code class="docutils literal notranslate"><span class="pre">base_seed</span></code> is a long generated by main process using its RNG (thereby,
consuming a RNG state mandatorily). However, seeds for other libraries may be
duplicated upon initializing workers (e.g., NumPy), causing each worker to return
identical random numbers. (See <a class="reference internal" href="notes/faq.html#dataloader-workers-random-seed"><span class="std std-ref">this section</span></a> in FAQ.).</p>
<p>In <code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code>, you may access the PyTorch seed set for each worker
with either <a class="reference internal" href="#torch.utils.data.get_worker_info" title="torch.utils.data.get_worker_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.utils.data.get_worker_info().seed</span></code></a>
or <a class="reference internal" href="torch.html#torch.initial_seed" title="torch.initial_seed"><code class="xref py py-func docutils literal notranslate"><span class="pre">torch.initial_seed()</span></code></a>, and use it to seed other libraries before data
loading.</p>
</div>
</div>
</div>
<div class="section" id="memory-pinning">
<h2>Memory Pinning<a class="headerlink" href="#memory-pinning" title="Permalink to this headline">¶</a></h2>
<p>Host to GPU copies are much faster when they originate from pinned (page-locked)
memory. See <a class="reference internal" href="notes/cuda.html#cuda-memory-pinning"><span class="std std-ref">Use pinned memory buffers</span></a> for more details on when and how to use
pinned memory generally.</p>
<p>For data loading, passing <code class="xref py py-attr docutils literal notranslate"><span class="pre">pin_memory=True</span></code> to a
<a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> will automatically put the fetched data
Tensors in pinned memory, and thus enables faster data transfer to CUDA-enabled
GPUs.</p>
<p>The default memory pinning logic only recognizes Tensors and maps and iterables
containing Tensors.  By default, if the pinning logic sees a batch that is a
custom type (which will occur if you have a <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> that returns a
custom batch type), or if each element of your batch is a custom type, the
pinning logic will not recognize them, and it will return that batch (or those
elements) without pinning the memory.  To enable memory pinning for custom
batch or data type(s), define a <code class="xref py py-meth docutils literal notranslate"><span class="pre">pin_memory()</span></code> method on your custom
type(s).</p>
<p>See the example below.</p>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="k">class</span> <span class="nc">SimpleCustomBatch</span><span class="p">:</span>
    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">data</span><span class="p">):</span>
        <span class="n">transposed_data</span> <span class="o">=</span> <span class="nb">list</span><span class="p">(</span><span class="nb">zip</span><span class="p">(</span><span class="o">*</span><span class="n">data</span><span class="p">))</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">inp</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">stack</span><span class="p">(</span><span class="n">transposed_data</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="mi">0</span><span class="p">)</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tgt</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">stack</span><span class="p">(</span><span class="n">transposed_data</span><span class="p">[</span><span class="mi">1</span><span class="p">],</span> <span class="mi">0</span><span class="p">)</span>

    <span class="c1"># custom memory pinning method on custom type</span>
    <span class="k">def</span> <span class="nf">pin_memory</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">inp</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">inp</span><span class="o">.</span><span class="n">pin_memory</span><span class="p">()</span>
        <span class="bp">self</span><span class="o">.</span><span class="n">tgt</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">tgt</span><span class="o">.</span><span class="n">pin_memory</span><span class="p">()</span>
        <span class="k">return</span> <span class="bp">self</span>

<span class="k">def</span> <span class="nf">collate_wrapper</span><span class="p">(</span><span class="n">batch</span><span class="p">):</span>
    <span class="k">return</span> <span class="n">SimpleCustomBatch</span><span class="p">(</span><span class="n">batch</span><span class="p">)</span>

<span class="n">inps</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">10</span> <span class="o">*</span> <span class="mi">5</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">float32</span><span class="p">)</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="n">tgts</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">arange</span><span class="p">(</span><span class="mi">10</span> <span class="o">*</span> <span class="mi">5</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">torch</span><span class="o">.</span><span class="n">float32</span><span class="p">)</span><span class="o">.</span><span class="n">view</span><span class="p">(</span><span class="mi">10</span><span class="p">,</span> <span class="mi">5</span><span class="p">)</span>
<span class="n">dataset</span> <span class="o">=</span> <span class="n">TensorDataset</span><span class="p">(</span><span class="n">inps</span><span class="p">,</span> <span class="n">tgts</span><span class="p">)</span>

<span class="n">loader</span> <span class="o">=</span> <span class="n">DataLoader</span><span class="p">(</span><span class="n">dataset</span><span class="p">,</span> <span class="n">batch_size</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">collate_fn</span><span class="o">=</span><span class="n">collate_wrapper</span><span class="p">,</span>
                    <span class="n">pin_memory</span><span class="o">=</span><span class="kc">True</span><span class="p">)</span>

<span class="k">for</span> <span class="n">batch_ndx</span><span class="p">,</span> <span class="n">sample</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">loader</span><span class="p">):</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">sample</span><span class="o">.</span><span class="n">inp</span><span class="o">.</span><span class="n">is_pinned</span><span class="p">())</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">sample</span><span class="o">.</span><span class="n">tgt</span><span class="o">.</span><span class="n">is_pinned</span><span class="p">())</span>
</pre></div>
</div>
<dl class="class">
<dt id="torch.utils.data.DataLoader">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">DataLoader</code><span class="sig-paren">(</span><em class="sig-param">dataset</em>, <em class="sig-param">batch_size=1</em>, <em class="sig-param">shuffle=False</em>, <em class="sig-param">sampler=None</em>, <em class="sig-param">batch_sampler=None</em>, <em class="sig-param">num_workers=0</em>, <em class="sig-param">collate_fn=None</em>, <em class="sig-param">pin_memory=False</em>, <em class="sig-param">drop_last=False</em>, <em class="sig-param">timeout=0</em>, <em class="sig-param">worker_init_fn=None</em>, <em class="sig-param">multiprocessing_context=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/dataloader.html#DataLoader"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.DataLoader" title="Permalink to this definition">¶</a></dt>
<dd><p>Data loader. Combines a dataset and a sampler, and provides an iterable over
the given dataset.</p>
<p>The <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> supports both map-style and
iterable-style datasets with single- or multi-process loading, customizing
loading order and optional automatic batching (collation) and memory pinning.</p>
<p>See <a class="reference internal" href="#module-torch.utils.data" title="torch.utils.data"><code class="xref py py-mod docutils literal notranslate"><span class="pre">torch.utils.data</span></code></a> documentation page for more details.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>dataset</strong> (<a class="reference internal" href="#torch.utils.data.Dataset" title="torch.utils.data.Dataset"><em>Dataset</em></a>) – dataset from which to load the data.</p></li>
<li><p><strong>batch_size</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><em>int</em></a><em>, </em><em>optional</em>) – how many samples per batch to load
(default: <code class="docutils literal notranslate"><span class="pre">1</span></code>).</p></li>
<li><p><strong>shuffle</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#bool" title="(in Python v3.8)"><em>bool</em></a><em>, </em><em>optional</em>) – set to <code class="docutils literal notranslate"><span class="pre">True</span></code> to have the data reshuffled
at every epoch (default: <code class="docutils literal notranslate"><span class="pre">False</span></code>).</p></li>
<li><p><strong>sampler</strong> (<a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><em>Sampler</em></a><em>, </em><em>optional</em>) – defines the strategy to draw samples from
the dataset. If specified, <code class="xref py py-attr docutils literal notranslate"><span class="pre">shuffle</span></code> must be <code class="docutils literal notranslate"><span class="pre">False</span></code>.</p></li>
<li><p><strong>batch_sampler</strong> (<a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><em>Sampler</em></a><em>, </em><em>optional</em>) – like <code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code>, but returns a batch of
indices at a time. Mutually exclusive with <code class="xref py py-attr docutils literal notranslate"><span class="pre">batch_size</span></code>,
<code class="xref py py-attr docutils literal notranslate"><span class="pre">shuffle</span></code>, <code class="xref py py-attr docutils literal notranslate"><span class="pre">sampler</span></code>, and <code class="xref py py-attr docutils literal notranslate"><span class="pre">drop_last</span></code>.</p></li>
<li><p><strong>num_workers</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><em>int</em></a><em>, </em><em>optional</em>) – how many subprocesses to use for data
loading. <code class="docutils literal notranslate"><span class="pre">0</span></code> means that the data will be loaded in the main process.
(default: <code class="docutils literal notranslate"><span class="pre">0</span></code>)</p></li>
<li><p><strong>collate_fn</strong> (<em>callable</em><em>, </em><em>optional</em>) – merges a list of samples to form a
mini-batch of Tensor(s).  Used when using batched loading from a
map-style dataset.</p></li>
<li><p><strong>pin_memory</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#bool" title="(in Python v3.8)"><em>bool</em></a><em>, </em><em>optional</em>) – If <code class="docutils literal notranslate"><span class="pre">True</span></code>, the data loader will copy Tensors
into CUDA pinned memory before returning them.  If your data elements
are a custom type, or your <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code> returns a batch that is a custom type,
see the example below.</p></li>
<li><p><strong>drop_last</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#bool" title="(in Python v3.8)"><em>bool</em></a><em>, </em><em>optional</em>) – set to <code class="docutils literal notranslate"><span class="pre">True</span></code> to drop the last incomplete batch,
if the dataset size is not divisible by the batch size. If <code class="docutils literal notranslate"><span class="pre">False</span></code> and
the size of dataset is not divisible by the batch size, then the last batch
will be smaller. (default: <code class="docutils literal notranslate"><span class="pre">False</span></code>)</p></li>
<li><p><strong>timeout</strong> (<em>numeric</em><em>, </em><em>optional</em>) – if positive, the timeout value for collecting a batch
from workers. Should always be non-negative. (default: <code class="docutils literal notranslate"><span class="pre">0</span></code>)</p></li>
<li><p><strong>worker_init_fn</strong> (<em>callable</em><em>, </em><em>optional</em>) – If not <code class="docutils literal notranslate"><span class="pre">None</span></code>, this will be called on each
worker subprocess with the worker id (an int in <code class="docutils literal notranslate"><span class="pre">[0,</span> <span class="pre">num_workers</span> <span class="pre">-</span> <span class="pre">1]</span></code>) as
input, after seeding and before data loading. (default: <code class="docutils literal notranslate"><span class="pre">None</span></code>)</p></li>
</ul>
</dd>
</dl>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>If the <code class="docutils literal notranslate"><span class="pre">spawn</span></code> start method is used, <code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code>
cannot be an unpicklable object, e.g., a lambda function. See
<a class="reference internal" href="notes/multiprocessing.html#multiprocessing-best-practices"><span class="std std-ref">Multiprocessing best practices</span></a> on more details related
to multiprocessing in PyTorch.</p>
</div>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p><code class="docutils literal notranslate"><span class="pre">len(dataloader)</span></code> heuristic is based on the length of the sampler used.
When <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code> is an <a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a>,
<code class="docutils literal notranslate"><span class="pre">len(dataset)</span></code> (if implemented) is returned instead, regardless
of multi-process loading configurations, because PyTorch trust
user <code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code> code in correctly handling multi-process
loading to avoid duplicate data. See <a class="reference internal" href="#dataset-types">Dataset Types</a> for more
details on these two types of datasets and how
<a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a> interacts with <a class="reference internal" href="#multi-process-data-loading">Multi-process data loading</a>.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.Dataset">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">Dataset</code><a class="reference internal" href="_modules/torch/utils/data/dataset.html#Dataset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.Dataset" title="Permalink to this definition">¶</a></dt>
<dd><p>An abstract class representing a <a class="reference internal" href="#torch.utils.data.Dataset" title="torch.utils.data.Dataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">Dataset</span></code></a>.</p>
<p>All datasets that represent a map from keys to data samples should subclass
it. All subclasses should overwrite <code class="xref py py-meth docutils literal notranslate"><span class="pre">__getitem__()</span></code>, supporting fetching a
data sample for a given key. Subclasses could also optionally overwrite
<code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code>, which is expected to return the size of the dataset by many
<a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><code class="xref py py-class docutils literal notranslate"><span class="pre">Sampler</span></code></a> implementations and the default options
of <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p><a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> by default constructs a index
sampler that yields integral indices.  To make it work with a map-style
dataset with non-integral indices/keys, a custom sampler must be provided.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.IterableDataset">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">IterableDataset</code><a class="reference internal" href="_modules/torch/utils/data/dataset.html#IterableDataset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.IterableDataset" title="Permalink to this definition">¶</a></dt>
<dd><p>An iterable Dataset.</p>
<p>All datasets that represent an iterable of data samples should subclass it.
Such form of datasets is particularly useful when data come from a stream.</p>
<p>All subclasses should overwrite <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code>, which would return an
iterator of samples in this dataset.</p>
<p>When a subclass is used with <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>, each
item in the dataset will be yielded from the <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>
iterator. When <code class="xref py py-attr docutils literal notranslate"><span class="pre">num_workers</span> <span class="pre">&gt;</span> <span class="pre">0</span></code>, each worker process will have a
different copy of the dataset object, so it is often desired to configure
each copy independently to avoid having duplicate data returned from the
workers. <a class="reference internal" href="#torch.utils.data.get_worker_info" title="torch.utils.data.get_worker_info"><code class="xref py py-func docutils literal notranslate"><span class="pre">get_worker_info()</span></code></a>, when called in a worker
process, returns information about the worker. It can be used in either the
dataset’s <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code> method or the <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> ‘s
<code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code> option to modify each copy’s behavior.</p>
<p>Example 1: splitting workload across all workers in <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyIterableDataset</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">IterableDataset</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">super</span><span class="p">(</span><span class="n">MyIterableDataset</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
<span class="gp">... </span>        <span class="k">assert</span> <span class="n">end</span> <span class="o">&gt;</span> <span class="n">start</span><span class="p">,</span> <span class="s2">&quot;this example code only works with end &gt;= start&quot;</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">start</span> <span class="o">=</span> <span class="n">start</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">end</span> <span class="o">=</span> <span class="n">end</span>
<span class="gp">...</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="n">worker_info</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">get_worker_info</span><span class="p">()</span>
<span class="gp">... </span>        <span class="k">if</span> <span class="n">worker_info</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">:</span>  <span class="c1"># single-process data loading, return the full iterator</span>
<span class="gp">... </span>            <span class="n">iter_start</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">start</span>
<span class="gp">... </span>            <span class="n">iter_end</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span>
<span class="gp">... </span>        <span class="k">else</span><span class="p">:</span>  <span class="c1"># in a worker process</span>
<span class="gp">... </span>            <span class="c1"># split workload</span>
<span class="gp">... </span>            <span class="n">per_worker</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">ceil</span><span class="p">((</span><span class="bp">self</span><span class="o">.</span><span class="n">end</span> <span class="o">-</span> <span class="bp">self</span><span class="o">.</span><span class="n">start</span><span class="p">)</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">worker_info</span><span class="o">.</span><span class="n">num_workers</span><span class="p">)))</span>
<span class="gp">... </span>            <span class="n">worker_id</span> <span class="o">=</span> <span class="n">worker_info</span><span class="o">.</span><span class="n">id</span>
<span class="gp">... </span>            <span class="n">iter_start</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">start</span> <span class="o">+</span> <span class="n">worker_id</span> <span class="o">*</span> <span class="n">per_worker</span>
<span class="gp">... </span>            <span class="n">iter_end</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">iter_start</span> <span class="o">+</span> <span class="n">per_worker</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span><span class="p">)</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="n">iter_start</span><span class="p">,</span> <span class="n">iter_end</span><span class="p">))</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># should give same set of data as range(3, 7), i.e., [3, 4, 5, 6].</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ds</span> <span class="o">=</span> <span class="n">MyIterableDataset</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="mi">7</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Single-process loading</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">DataLoader</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">0</span><span class="p">)))</span>
<span class="go">[3, 4, 5, 6]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Mult-process loading with two worker processes</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Worker 0 fetched [3, 4].  Worker 1 fetched [5, 6].</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">DataLoader</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">2</span><span class="p">)))</span>
<span class="go">[3, 5, 4, 6]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># With even more workers</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">DataLoader</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">20</span><span class="p">)))</span>
<span class="go">[3, 4, 5, 6]</span>
</pre></div>
</div>
<p>Example 2: splitting workload across all workers using <code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code>:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="k">class</span> <span class="nc">MyIterableDataset</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">IterableDataset</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">):</span>
<span class="gp">... </span>        <span class="nb">super</span><span class="p">(</span><span class="n">MyIterableDataset</span><span class="p">)</span><span class="o">.</span><span class="fm">__init__</span><span class="p">()</span>
<span class="gp">... </span>        <span class="k">assert</span> <span class="n">end</span> <span class="o">&gt;</span> <span class="n">start</span><span class="p">,</span> <span class="s2">&quot;this example code only works with end &gt;= start&quot;</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">start</span> <span class="o">=</span> <span class="n">start</span>
<span class="gp">... </span>        <span class="bp">self</span><span class="o">.</span><span class="n">end</span> <span class="o">=</span> <span class="n">end</span>
<span class="gp">...</span>
<span class="gp">... </span>    <span class="k">def</span> <span class="fm">__iter__</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
<span class="gp">... </span>        <span class="k">return</span> <span class="nb">iter</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">start</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span><span class="p">))</span>
<span class="gp">...</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># should give same set of data as range(3, 7), i.e., [3, 4, 5, 6].</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">ds</span> <span class="o">=</span> <span class="n">MyIterableDataset</span><span class="p">(</span><span class="n">start</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="mi">7</span><span class="p">)</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Single-process loading</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">DataLoader</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">0</span><span class="p">)))</span>
<span class="go">[3, 4, 5, 6]</span>
<span class="go">&gt;&gt;&gt;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Directly doing multi-process loading yields duplicate data</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">DataLoader</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">2</span><span class="p">)))</span>
<span class="go">[3, 3, 4, 4, 5, 5, 6, 6]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Define a `worker_init_fn` that configures each dataset copy differently</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">def</span> <span class="nf">worker_init_fn</span><span class="p">(</span><span class="n">worker_id</span><span class="p">):</span>
<span class="gp">... </span>    <span class="n">worker_info</span> <span class="o">=</span> <span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">get_worker_info</span><span class="p">()</span>
<span class="gp">... </span>    <span class="n">dataset</span> <span class="o">=</span> <span class="n">worker_info</span><span class="o">.</span><span class="n">dataset</span>  <span class="c1"># the dataset copy in this worker process</span>
<span class="gp">... </span>    <span class="n">overall_start</span> <span class="o">=</span> <span class="n">dataset</span><span class="o">.</span><span class="n">start</span>
<span class="gp">... </span>    <span class="n">overall_end</span> <span class="o">=</span> <span class="n">dataset</span><span class="o">.</span><span class="n">end</span>
<span class="gp">... </span>    <span class="c1"># configure the dataset to only process the split workload</span>
<span class="gp">... </span>    <span class="n">per_worker</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">math</span><span class="o">.</span><span class="n">ceil</span><span class="p">((</span><span class="n">overall_end</span> <span class="o">-</span> <span class="n">overall_start</span><span class="p">)</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">worker_info</span><span class="o">.</span><span class="n">num_workers</span><span class="p">)))</span>
<span class="gp">... </span>    <span class="n">worker_id</span> <span class="o">=</span> <span class="n">worker_info</span><span class="o">.</span><span class="n">id</span>
<span class="gp">... </span>    <span class="n">dataset</span><span class="o">.</span><span class="n">start</span> <span class="o">=</span> <span class="n">overall_start</span> <span class="o">+</span> <span class="n">worker_id</span> <span class="o">*</span> <span class="n">per_worker</span>
<span class="gp">... </span>    <span class="n">dataset</span><span class="o">.</span><span class="n">end</span> <span class="o">=</span> <span class="nb">min</span><span class="p">(</span><span class="n">dataset</span><span class="o">.</span><span class="n">start</span> <span class="o">+</span> <span class="n">per_worker</span><span class="p">,</span> <span class="n">overall_end</span><span class="p">)</span>
<span class="gp">...</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Mult-process loading with the custom `worker_init_fn`</span>
<span class="gp">&gt;&gt;&gt; </span><span class="c1"># Worker 0 fetched [3, 4].  Worker 1 fetched [5, 6].</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">DataLoader</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">2</span><span class="p">,</span> <span class="n">worker_init_fn</span><span class="o">=</span><span class="n">worker_init_fn</span><span class="p">)))</span>
<span class="go">[3, 5, 4, 6]</span>

<span class="gp">&gt;&gt;&gt; </span><span class="c1"># With even more workers</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">print</span><span class="p">(</span><span class="nb">list</span><span class="p">(</span><span class="n">torch</span><span class="o">.</span><span class="n">utils</span><span class="o">.</span><span class="n">data</span><span class="o">.</span><span class="n">DataLoader</span><span class="p">(</span><span class="n">ds</span><span class="p">,</span> <span class="n">num_workers</span><span class="o">=</span><span class="mi">20</span><span class="p">,</span> <span class="n">worker_init_fn</span><span class="o">=</span><span class="n">worker_init_fn</span><span class="p">)))</span>
<span class="go">[3, 4, 5, 6]</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.TensorDataset">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">TensorDataset</code><span class="sig-paren">(</span><em class="sig-param">*tensors</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/dataset.html#TensorDataset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.TensorDataset" title="Permalink to this definition">¶</a></dt>
<dd><p>Dataset wrapping tensors.</p>
<p>Each sample will be retrieved by indexing tensors along the first dimension.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><p><strong>*tensors</strong> (<a class="reference internal" href="tensors.html#torch.Tensor" title="torch.Tensor"><em>Tensor</em></a>) – tensors that have the same size of the first dimension.</p>
</dd>
</dl>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.ConcatDataset">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">ConcatDataset</code><span class="sig-paren">(</span><em class="sig-param">datasets</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/dataset.html#ConcatDataset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.ConcatDataset" title="Permalink to this definition">¶</a></dt>
<dd><p>Dataset as a concatenation of multiple datasets.</p>
<p>This class is useful to assemble different existing datasets.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><p><strong>datasets</strong> (<em>sequence</em>) – List of datasets to be concatenated</p>
</dd>
</dl>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.ChainDataset">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">ChainDataset</code><span class="sig-paren">(</span><em class="sig-param">datasets</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/dataset.html#ChainDataset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.ChainDataset" title="Permalink to this definition">¶</a></dt>
<dd><p>Dataset for chainning multiple <a class="reference internal" href="#torch.utils.data.IterableDataset" title="torch.utils.data.IterableDataset"><code class="xref py py-class docutils literal notranslate"><span class="pre">IterableDataset</span></code></a> s.</p>
<p>This class is useful to assemble different existing dataset streams. The
chainning operation is done on-the-fly, so concatenating large-scale
datasets with this class will be efficient.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><p><strong>datasets</strong> (<em>iterable of IterableDataset</em>) – datasets to be chained together</p>
</dd>
</dl>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.Subset">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">Subset</code><span class="sig-paren">(</span><em class="sig-param">dataset</em>, <em class="sig-param">indices</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/dataset.html#Subset"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.Subset" title="Permalink to this definition">¶</a></dt>
<dd><p>Subset of a dataset at specified indices.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>dataset</strong> (<a class="reference internal" href="#torch.utils.data.Dataset" title="torch.utils.data.Dataset"><em>Dataset</em></a>) – The whole Dataset</p></li>
<li><p><strong>indices</strong> (<em>sequence</em>) – Indices in the whole set selected for subset</p></li>
</ul>
</dd>
</dl>
</dd></dl>

<dl class="function">
<dt id="torch.utils.data.get_worker_info">
<code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">get_worker_info</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/_utils/worker.html#get_worker_info"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.get_worker_info" title="Permalink to this definition">¶</a></dt>
<dd><p>Returns the information about the current
<a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a> iterator worker process.</p>
<p>When called in a worker, this returns an object guaranteed to have the
following attributes:</p>
<ul class="simple">
<li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">id</span></code>: the current worker id.</p></li>
<li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">num_workers</span></code>: the total number of workers.</p></li>
<li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">seed</span></code>: the random seed set for the current worker. This value is
determined by main process RNG and the worker id. See
<a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>’s documentation for more details.</p></li>
<li><p><code class="xref py py-attr docutils literal notranslate"><span class="pre">dataset</span></code>: the copy of the dataset object in <strong>this</strong> process. Note
that this will be a different object in a different process than the one
in the main process.</p></li>
</ul>
<p>When called in the main process, this returns <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>When used in a <code class="xref py py-attr docutils literal notranslate"><span class="pre">worker_init_fn</span></code> passed over to
<a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>, this method can be useful to
set up each worker process differently, for instance, using <code class="docutils literal notranslate"><span class="pre">worker_id</span></code>
to configure the <code class="docutils literal notranslate"><span class="pre">dataset</span></code> object to only read a specific fraction of a
sharded dataset, or use <code class="docutils literal notranslate"><span class="pre">seed</span></code> to seed other libraries used in dataset
code (e.g., NumPy).</p>
</div>
</dd></dl>

<dl class="function">
<dt id="torch.utils.data.random_split">
<code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">random_split</code><span class="sig-paren">(</span><em class="sig-param">dataset</em>, <em class="sig-param">lengths</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/dataset.html#random_split"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.random_split" title="Permalink to this definition">¶</a></dt>
<dd><p>Randomly split a dataset into non-overlapping new datasets of given lengths.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>dataset</strong> (<a class="reference internal" href="#torch.utils.data.Dataset" title="torch.utils.data.Dataset"><em>Dataset</em></a>) – Dataset to be split</p></li>
<li><p><strong>lengths</strong> (<em>sequence</em>) – lengths of splits to be produced</p></li>
</ul>
</dd>
</dl>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.Sampler">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">Sampler</code><span class="sig-paren">(</span><em class="sig-param">data_source</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/sampler.html#Sampler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.Sampler" title="Permalink to this definition">¶</a></dt>
<dd><p>Base class for all Samplers.</p>
<p>Every Sampler subclass has to provide an <code class="xref py py-meth docutils literal notranslate"><span class="pre">__iter__()</span></code> method, providing a
way to iterate over indices of dataset elements, and a <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code> method
that returns the length of the returned iterators.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>The <code class="xref py py-meth docutils literal notranslate"><span class="pre">__len__()</span></code> method isn’t strictly required by
<a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>, but is expected in any
calculation involving the length of a <a class="reference internal" href="#torch.utils.data.DataLoader" title="torch.utils.data.DataLoader"><code class="xref py py-class docutils literal notranslate"><span class="pre">DataLoader</span></code></a>.</p>
</div>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.SequentialSampler">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">SequentialSampler</code><span class="sig-paren">(</span><em class="sig-param">data_source</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/sampler.html#SequentialSampler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.SequentialSampler" title="Permalink to this definition">¶</a></dt>
<dd><p>Samples elements sequentially, always in the same order.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><p><strong>data_source</strong> (<a class="reference internal" href="#torch.utils.data.Dataset" title="torch.utils.data.Dataset"><em>Dataset</em></a>) – dataset to sample from</p>
</dd>
</dl>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.RandomSampler">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">RandomSampler</code><span class="sig-paren">(</span><em class="sig-param">data_source</em>, <em class="sig-param">replacement=False</em>, <em class="sig-param">num_samples=None</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/sampler.html#RandomSampler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.RandomSampler" title="Permalink to this definition">¶</a></dt>
<dd><p>Samples elements randomly. If without replacement, then sample from a shuffled dataset.
If with replacement, then user can specify <code class="xref py py-attr docutils literal notranslate"><span class="pre">num_samples</span></code> to draw.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>data_source</strong> (<a class="reference internal" href="#torch.utils.data.Dataset" title="torch.utils.data.Dataset"><em>Dataset</em></a>) – dataset to sample from</p></li>
<li><p><strong>replacement</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#bool" title="(in Python v3.8)"><em>bool</em></a>) – samples are drawn with replacement if <code class="docutils literal notranslate"><span class="pre">True</span></code>, default=``False``</p></li>
<li><p><strong>num_samples</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><em>int</em></a>) – number of samples to draw, default=`len(dataset)`. This argument
is supposed to be specified only when <cite>replacement</cite> is <code class="docutils literal notranslate"><span class="pre">True</span></code>.</p></li>
</ul>
</dd>
</dl>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.SubsetRandomSampler">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">SubsetRandomSampler</code><span class="sig-paren">(</span><em class="sig-param">indices</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/sampler.html#SubsetRandomSampler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.SubsetRandomSampler" title="Permalink to this definition">¶</a></dt>
<dd><p>Samples elements randomly from a given list of indices, without replacement.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><p><strong>indices</strong> (<em>sequence</em>) – a sequence of indices</p>
</dd>
</dl>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.WeightedRandomSampler">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">WeightedRandomSampler</code><span class="sig-paren">(</span><em class="sig-param">weights</em>, <em class="sig-param">num_samples</em>, <em class="sig-param">replacement=True</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/sampler.html#WeightedRandomSampler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.WeightedRandomSampler" title="Permalink to this definition">¶</a></dt>
<dd><p>Samples elements from <code class="docutils literal notranslate"><span class="pre">[0,..,len(weights)-1]</span></code> with given probabilities (weights).</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>weights</strong> (<em>sequence</em>) – a sequence of weights, not necessary summing up to one</p></li>
<li><p><strong>num_samples</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><em>int</em></a>) – number of samples to draw</p></li>
<li><p><strong>replacement</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#bool" title="(in Python v3.8)"><em>bool</em></a>) – if <code class="docutils literal notranslate"><span class="pre">True</span></code>, samples are drawn with replacement.
If not, they are drawn without replacement, which means that when a
sample index is drawn for a row, it cannot be drawn again for that row.</p></li>
</ul>
</dd>
</dl>
<p class="rubric">Example</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">WeightedRandomSampler</span><span class="p">([</span><span class="mf">0.1</span><span class="p">,</span> <span class="mf">0.9</span><span class="p">,</span> <span class="mf">0.4</span><span class="p">,</span> <span class="mf">0.7</span><span class="p">,</span> <span class="mf">3.0</span><span class="p">,</span> <span class="mf">0.6</span><span class="p">],</span> <span class="mi">5</span><span class="p">,</span> <span class="n">replacement</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
<span class="go">[4, 4, 1, 4, 5]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">WeightedRandomSampler</span><span class="p">([</span><span class="mf">0.9</span><span class="p">,</span> <span class="mf">0.4</span><span class="p">,</span> <span class="mf">0.05</span><span class="p">,</span> <span class="mf">0.2</span><span class="p">,</span> <span class="mf">0.3</span><span class="p">,</span> <span class="mf">0.1</span><span class="p">],</span> <span class="mi">5</span><span class="p">,</span> <span class="n">replacement</span><span class="o">=</span><span class="kc">False</span><span class="p">))</span>
<span class="go">[0, 1, 4, 3, 2]</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.BatchSampler">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.</code><code class="sig-name descname">BatchSampler</code><span class="sig-paren">(</span><em class="sig-param">sampler</em>, <em class="sig-param">batch_size</em>, <em class="sig-param">drop_last</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/sampler.html#BatchSampler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.BatchSampler" title="Permalink to this definition">¶</a></dt>
<dd><p>Wraps another sampler to yield a mini-batch of indices.</p>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>sampler</strong> (<a class="reference internal" href="#torch.utils.data.Sampler" title="torch.utils.data.Sampler"><em>Sampler</em></a>) – Base sampler.</p></li>
<li><p><strong>batch_size</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#int" title="(in Python v3.8)"><em>int</em></a>) – Size of mini-batch.</p></li>
<li><p><strong>drop_last</strong> (<a class="reference external" href="https://docs.python.org/3/library/functions.html#bool" title="(in Python v3.8)"><em>bool</em></a>) – If <code class="docutils literal notranslate"><span class="pre">True</span></code>, the sampler will drop the last batch if
its size would be less than <code class="docutils literal notranslate"><span class="pre">batch_size</span></code></p></li>
</ul>
</dd>
</dl>
<p class="rubric">Example</p>
<div class="doctest highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">BatchSampler</span><span class="p">(</span><span class="n">SequentialSampler</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)),</span> <span class="n">batch_size</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">drop_last</span><span class="o">=</span><span class="kc">False</span><span class="p">))</span>
<span class="go">[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="nb">list</span><span class="p">(</span><span class="n">BatchSampler</span><span class="p">(</span><span class="n">SequentialSampler</span><span class="p">(</span><span class="nb">range</span><span class="p">(</span><span class="mi">10</span><span class="p">)),</span> <span class="n">batch_size</span><span class="o">=</span><span class="mi">3</span><span class="p">,</span> <span class="n">drop_last</span><span class="o">=</span><span class="kc">True</span><span class="p">))</span>
<span class="go">[[0, 1, 2], [3, 4, 5], [6, 7, 8]]</span>
</pre></div>
</div>
</dd></dl>

<dl class="class">
<dt id="torch.utils.data.distributed.DistributedSampler">
<em class="property">class </em><code class="sig-prename descclassname">torch.utils.data.distributed.</code><code class="sig-name descname">DistributedSampler</code><span class="sig-paren">(</span><em class="sig-param">dataset</em>, <em class="sig-param">num_replicas=None</em>, <em class="sig-param">rank=None</em>, <em class="sig-param">shuffle=True</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/torch/utils/data/distributed.html#DistributedSampler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#torch.utils.data.distributed.DistributedSampler" title="Permalink to this definition">¶</a></dt>
<dd><p>Sampler that restricts data loading to a subset of the dataset.</p>
<p>It is especially useful in conjunction with
<a class="reference internal" href="nn.html#torch.nn.parallel.DistributedDataParallel" title="torch.nn.parallel.DistributedDataParallel"><code class="xref py py-class docutils literal notranslate"><span class="pre">torch.nn.parallel.DistributedDataParallel</span></code></a>. In such case, each
process can pass a DistributedSampler instance as a DataLoader sampler,
and load a subset of the original dataset that is exclusive to it.</p>
<div class="admonition note">
<p class="admonition-title">Note</p>
<p>Dataset is assumed to be of constant size.</p>
</div>
<dl class="field-list simple">
<dt class="field-odd">Parameters</dt>
<dd class="field-odd"><ul class="simple">
<li><p><strong>dataset</strong> – Dataset used for sampling.</p></li>
<li><p><strong>num_replicas</strong> (<em>optional</em>) – Number of processes participating in
distributed training.</p></li>
<li><p><strong>rank</strong> (<em>optional</em>) – Rank of the current process within num_replicas.</p></li>
<li><p><strong>shuffle</strong> (<em>optional</em>) – If true (default), sampler will shuffle the indices</p></li>
</ul>
</dd>
</dl>
<div class="admonition warning">
<p class="admonition-title">Warning</p>
<p>In distributed mode, calling the <code class="docutils literal notranslate"><span class="pre">set_epoch</span></code> method is needed to
make shuffling work; each process will use the same random seed
otherwise.</p>
</div>
<p>Example:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="n">sampler</span> <span class="o">=</span> <span class="n">DistributedSampler</span><span class="p">(</span><span class="n">dataset</span><span class="p">)</span> <span class="k">if</span> <span class="n">is_distributed</span> <span class="k">else</span> <span class="kc">None</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">loader</span> <span class="o">=</span> <span class="n">DataLoader</span><span class="p">(</span><span class="n">dataset</span><span class="p">,</span> <span class="n">shuffle</span><span class="o">=</span><span class="p">(</span><span class="n">sampler</span> <span class="ow">is</span> <span class="kc">None</span><span class="p">),</span>
<span class="gp">... </span>                    <span class="n">sampler</span><span class="o">=</span><span class="n">sampler</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="k">for</span> <span class="n">epoch</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">start_epoch</span><span class="p">,</span> <span class="n">n_epochs</span><span class="p">):</span>
<span class="gp">... </span>    <span class="k">if</span> <span class="n">is_distributed</span><span class="p">:</span>
</pre></div>
</div>
</dd></dl>

</div>
</div>


             </article>
             
            </div>
            <footer>
  
    <div class="rst-footer-buttons" role="navigation" aria-label="footer navigation">
      
        <a href="dlpack.html" class="btn btn-neutral float-right" title="torch.utils.dlpack" accesskey="n" rel="next">Next <img src="_static/images/chevron-right-orange.svg" class="next-page"></a>
      
      
        <a href="cpp_extension.html" class="btn btn-neutral" title="torch.utils.cpp_extension" accesskey="p" rel="prev"><img src="_static/images/chevron-right-orange.svg" class="previous-page"> Previous</a>
      
    </div>
  

  

    <hr>

  

  <div role="contentinfo">
    <p>
        &copy; Copyright 2019, Torch Contributors.

    </p>
  </div>
    
      <div>
        Built with <a href="http://sphinx-doc.org/">Sphinx</a> using a <a href="https://github.com/rtfd/sphinx_rtd_theme">theme</a> provided by <a href="https://readthedocs.org">Read the Docs</a>.
      </div>
     

</footer>

          </div>
        </div>

        <div class="pytorch-content-right" id="pytorch-content-right">
          <div class="pytorch-right-menu" id="pytorch-right-menu">
            <div class="pytorch-side-scroll" id="pytorch-side-scroll-right">
              <ul>
<li><a class="reference internal" href="#">torch.utils.data</a><ul>
<li><a class="reference internal" href="#dataset-types">Dataset Types</a><ul>
<li><a class="reference internal" href="#map-style-datasets">Map-style datasets</a></li>
<li><a class="reference internal" href="#iterable-style-datasets">Iterable-style datasets</a></li>
</ul>
</li>
<li><a class="reference internal" href="#data-loading-order-and-sampler">Data Loading Order and <code class="xref py py-class docutils literal notranslate"><span class="pre">Sampler</span></code></a></li>
<li><a class="reference internal" href="#loading-batched-and-non-batched-data">Loading Batched and Non-Batched Data</a><ul>
<li><a class="reference internal" href="#automatic-batching-default">Automatic batching (default)</a></li>
<li><a class="reference internal" href="#disable-automatic-batching">Disable automatic batching</a></li>
<li><a class="reference internal" href="#working-with-collate-fn">Working with <code class="xref py py-attr docutils literal notranslate"><span class="pre">collate_fn</span></code></a></li>
</ul>
</li>
<li><a class="reference internal" href="#single-and-multi-process-data-loading">Single- and Multi-process Data Loading</a><ul>
<li><a class="reference internal" href="#single-process-data-loading-default">Single-process data loading (default)</a></li>
<li><a class="reference internal" href="#multi-process-data-loading">Multi-process data loading</a><ul>
<li><a class="reference internal" href="#platform-specific-behaviors">Platform-specific behaviors</a></li>
<li><a class="reference internal" href="#randomness-in-multi-process-data-loading">Randomness in multi-process data loading</a></li>
</ul>
</li>
</ul>
</li>
<li><a class="reference internal" href="#memory-pinning">Memory Pinning</a></li>
</ul>
</li>
</ul>

            </div>
          </div>
        </div>
      </section>
    </div>

  


  

     
       <script type="text/javascript" id="documentation_options" data-url_root="./" src="_static/documentation_options.js"></script>
         <script src="_static/jquery.js"></script>
         <script src="_static/underscore.js"></script>
         <script src="_static/doctools.js"></script>
         <script src="_static/language_data.js"></script>
     

  

  <script type="text/javascript" src="_static/js/vendor/popper.min.js"></script>
  <script type="text/javascript" src="_static/js/vendor/bootstrap.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/list.js/1.5.0/list.min.js"></script>
  <script type="text/javascript" src="_static/js/theme.js"></script>

  <script type="text/javascript">
      jQuery(function () {
          SphinxRtdTheme.Navigation.enable(true);
      });
  </script>
 
<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-90545585-1', 'auto');
  ga('send', 'pageview');

</script>

<script async src="https://www.googletagmanager.com/gtag/js?id=UA-117752657-2"></script>

<script>
  window.dataLayer = window.dataLayer || [];

  function gtag(){dataLayer.push(arguments);}

  gtag('js', new Date());
  gtag('config', 'UA-117752657-2');
</script>

<img height="1" width="1" style="border-style:none;" alt="" src="https://www.googleadservices.com/pagead/conversion/795629140/?label=txkmCPmdtosBENSssfsC&amp;guid=ON&amp;script=0"/>


  <!-- Begin Footer -->

  <div class="container-fluid docs-tutorials-resources" id="docs-tutorials-resources">
    <div class="container">
      <div class="row">
        <div class="col-md-4 text-center">
          <h2>Docs</h2>
          <p>Access comprehensive developer documentation for PyTorch</p>
          <a class="with-right-arrow" href="https://pytorch.org/docs/stable/index.html">View Docs</a>
        </div>

        <div class="col-md-4 text-center">
          <h2>Tutorials</h2>
          <p>Get in-depth tutorials for beginners and advanced developers</p>
          <a class="with-right-arrow" href="https://pytorch.org/tutorials">View Tutorials</a>
        </div>

        <div class="col-md-4 text-center">
          <h2>Resources</h2>
          <p>Find development resources and get your questions answered</p>
          <a class="with-right-arrow" href="https://pytorch.org/resources">View Resources</a>
        </div>
      </div>
    </div>
  </div>

  <footer class="site-footer">
    <div class="container footer-container">
      <div class="footer-logo-wrapper">
        <a href="https://pytorch.org/" class="footer-logo"></a>
      </div>

      <div class="footer-links-wrapper">
        <div class="footer-links-col">
          <ul>
            <li class="list-title"><a href="https://pytorch.org/">PyTorch</a></li>
            <li><a href="https://pytorch.org/get-started">Get Started</a></li>
            <li><a href="https://pytorch.org/features">Features</a></li>
            <li><a href="https://pytorch.org/ecosystem">Ecosystem</a></li>
            <li><a href="https://pytorch.org/blog/">Blog</a></li>
            <li><a href="https://github.com/pytorch/pytorch/blob/master/CONTRIBUTING.md">Contributing</a></li>
          </ul>
        </div>

        <div class="footer-links-col">
          <ul>
            <li class="list-title"><a href="https://pytorch.org/resources">Resources</a></li>
            <li><a href="https://pytorch.org/tutorials">Tutorials</a></li>
            <li><a href="https://pytorch.org/docs/stable/index.html">Docs</a></li>
            <li><a href="https://discuss.pytorch.org" target="_blank">Discuss</a></li>
            <li><a href="https://github.com/pytorch/pytorch/issues" target="_blank">Github Issues</a></li>
            <li><a href="https://pytorch.org/assets/brand-guidelines/PyTorch-Brand-Guidelines.pdf" target="_blank">Brand Guidelines</a></li>
          </ul>
        </div>

        <div class="footer-links-col follow-us-col">
          <ul>
            <li class="list-title">Stay Connected</li>
            <li>
              <div id="mc_embed_signup">
                <form
                  action="https://twitter.us14.list-manage.com/subscribe/post?u=75419c71fe0a935e53dfa4a3f&id=91d0dccd39"
                  method="post"
                  id="mc-embedded-subscribe-form"
                  name="mc-embedded-subscribe-form"
                  class="email-subscribe-form validate"
                  target="_blank"
                  novalidate>
                  <div id="mc_embed_signup_scroll" class="email-subscribe-form-fields-wrapper">
                    <div class="mc-field-group">
                      <label for="mce-EMAIL" style="display:none;">Email Address</label>
                      <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL" placeholder="Email Address">
                    </div>

                    <div id="mce-responses" class="clear">
                      <div class="response" id="mce-error-response" style="display:none"></div>
                      <div class="response" id="mce-success-response" style="display:none"></div>
                    </div>    <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->

                    <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_75419c71fe0a935e53dfa4a3f_91d0dccd39" tabindex="-1" value=""></div>

                    <div class="clear">
                      <input type="submit" value="" name="subscribe" id="mc-embedded-subscribe" class="button email-subscribe-button">
                    </div>
                  </div>
                </form>
              </div>

            </li>
          </ul>

          <div class="footer-social-icons">
            <a href="https://www.facebook.com/pytorch" target="_blank" class="facebook"></a>
            <a href="https://twitter.com/pytorch" target="_blank" class="twitter"></a>
            <a href="https://www.youtube.com/pytorch" target="_blank" class="youtube"></a>
          </div>
        </div>
      </div>
    </div>
  </footer>

  <div class="cookie-banner-wrapper">
  <div class="container">
    <p class="gdpr-notice">To analyze traffic and optimize your experience, we serve cookies on this site. By clicking or navigating, you agree to allow our usage of cookies. As the current maintainers of this site, Facebook’s Cookies Policy applies. Learn more, including about available controls: <a href="https://www.facebook.com/policies/cookies/">Cookies Policy</a>.</p>
    <img class="close-button" src="_static/images/pytorch-x.svg">
  </div>
</div>

  <!-- End Footer -->

  <!-- Begin Mobile Menu -->

  <div class="mobile-main-menu">
    <div class="container-fluid">
      <div class="container">
        <div class="mobile-main-menu-header-container">
          <a class="header-logo" href="https://pytorch.org/" aria-label="PyTorch"></a>
          <a class="main-menu-close-button" href="#" data-behavior="close-mobile-menu"></a>
        </div>
      </div>
    </div>

    <div class="mobile-main-menu-links-container">
      <div class="main-menu">
        <ul>
          <li>
            <a href="https://pytorch.org/get-started">Get Started</a>
          </li>

          <li>
            <a href="https://pytorch.org/features">Features</a>
          </li>

          <li>
            <a href="https://pytorch.org/ecosystem">Ecosystem</a>
          </li>

          <li>
            <a href="https://pytorch.org/mobile">Mobile</a>
          </li>

          <li>
            <a href="https://pytorch.org/hub">PyTorch Hub</a>
          </li>

          <li>
            <a href="https://pytorch.org/blog/">Blog</a>
          </li>

          <li>
            <a href="https://pytorch.org/tutorials">Tutorials</a>
          </li>

          <li class="active">
            <a href="https://pytorch.org/docs/stable/index.html">Docs</a>
          </li>

          <li>
            <a href="https://pytorch.org/resources">Resources</a>
          </li>

          <li>
            <a href="https://github.com/pytorch/pytorch">Github</a>
          </li>
        </ul>
      </div>
    </div>
  </div>

  <!-- End Mobile Menu -->

  <script type="text/javascript" src="_static/js/vendor/anchor.min.js"></script>

  <script type="text/javascript">
    $(document).ready(function() {
      mobileMenu.bind();
      mobileTOC.bind();
      pytorchAnchors.bind();
      sideMenus.bind();
      scrollToAnchor.bind();
      highlightNavigation.bind();
      mainMenuDropdown.bind();
      filterTags.bind();

      // Remove any empty p tags that Sphinx adds
      $("[data-tags='null']").remove();

      // Add class to links that have code blocks, since we cannot create links in code blocks
      $("article.pytorch-article a span.pre").each(function(e) {
        $(this).closest("a").addClass("has-code");
      });
    })
  </script>
</body>
</html>